<template>
  <div class="app-container">
    <div class="handle-box">
      <div class="pull-left">
        <el-button type="danger" @click="add">
          <i class="icon icon-tianjia"></i> 添加管理员
        </el-button>
      </div>
      <div class="pull-right">
        <el-input v-model="select_word" placeholder="筛选关键词" class="handle-input"></el-input>
        <el-date-picker
          v-model="select_date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="最后开始日期"
          end-placeholder="最后结束日期"
          :default-time="['00:00:00', '23:59:59']"
          :value-format="'yyyy-MM-dd HH:mm:ss'">
        </el-date-picker>
        <el-select v-model="select_type" clearable placeholder="状态" class="handle-select">
          <el-option
            v-for="(item, index) in typeList"
            :key="index"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary" icon="search" @click="search">搜索</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      border
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      v-loading="listLoading">
      <el-table-column prop="username" label="管理员账号"></el-table-column>
      <el-table-column prop="type" label="群组">
        <template slot-scope="scope">
          <a class="pointer" @click="checkGroup(scope.row)">
            <el-tag type="primary" disable-transitions>
              <span>{{ scope.row.group_name }}</span>
            </el-tag>
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="tag" label="状态">
        <template slot-scope="scope">
          {{scope.row.status|array_filter(typeList)}}
        </template>
      </el-table-column>
      <el-table-column label="最后登陆IP">
        <template slot-scope="scope">
          {{scope.row.last_ip|empty('--')}}
        </template>
      </el-table-column>
      <el-table-column prop="last_date" label="最后登陆时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" class="mt-5">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)" class="mt-5">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="tableData.length"
      background
      layout="prev, pager, next"
      :total="totals"
      :page-size="per_page"
      class="mt-10"
      @current-change="currentChange">
    </el-pagination>
    <!-- 编辑弹出框 -->
    <el-dialog
      title="编辑管理员"
      :visible.sync="editVisible"
      width="520px"
      :show-close="false">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="120px"
        class="form"
        auto-complete="off" >
        <el-form-item label="管理员账号" prop="username">
          <el-input v-model="form.username" height="120" placeholder="管理员账号"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" prop="password">
          <el-input v-model="form.password" placeholder="管理员密码" show-password></el-input>
          <a class="pointer" @click="createPassword">生成密码</a>
        </el-form-item>
        <el-form-item label="管理员昵称" prop="real_name">
          <el-input v-model="form.nickname" height="120" placeholder="管理员昵称"></el-input>
        </el-form-item>
        <el-form-item label="权限组">
          <el-select v-model="form.gid" placeholder="请选权限组">
            <el-option :label="item.group_name" :value="item.id" :key="index" v-for="(item, index) in groupList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <!-- <el-radio label="未审核" value="0"></el-radio> -->
            <el-radio label="正常" value="1"></el-radio>
            <el-radio label="被封" value="2"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="mt-20">
          <el-button type="primary" @click="saveEdit('form')">提交</el-button>
          <el-button @click="cancel('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 删除提示框 -->
    <el-dialog
      :visible.sync="delVisible"
      title="提示"
      width="20%"
      center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRow">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { edit, save, group, del } from '@/api/admin'
import { getUsers } from '@/api/group'

export default {
  filters: {
    filterGroup: function(items, id) {
      if (!items) return
      items = items.filter(item => item.id === id)[0]
      return items.title
    }
  },
  data() {
    return {
      tableData: [],
      editVisible: false,
      delVisible: false,
      detailVisible: false,
      select_word: '',
      select_type: '',
      select_date: '',
      current_page: 1,
      last_page: 0,
      per_page: 5,
      totals: 0,
      row: [],
      is_search: false,
      delList: [],
      detail: [],
      form: {
        id: 0,
        username: '',
        nickname: '',
        password: '',
        status: '正常',
        gid: 1
      },
      rules: {
        admin_name: [{ required: true, message: '请输入账号', trigger: 'blur' }]
      },
      idx: 0,
      groupList: null,
      isDelAll: false,
      listLoading: true,
      typeList: [{
        id: 1,
        name: '正常'
      }, {
        id: 2,
        name: '禁用'
      }]
    }
  },
  computed: {
    metaTitle() {
      return this.$route.meta.title
    }
  },
  created() {
    this.getUsers()
    this.getGroupList()
  },
  methods: {
    createPassword() {
      const text = [
        'abcdefghijklmnopqrstuvwxyz',
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        '1234567890'
      ]
      const rand = function(min, max) {
        return Math.floor(Math.max(min, Math.random() * (max + 1)))
      }
      const len = 16
      let pw = ''
      for (let i = 0; i < len; ++i) {
        const strpos = rand(0, 2)
        pw += text[strpos].charAt(rand(0, text[strpos].length))
      }
      this.form.password = pw
    },
    getGroupList() {
      group().then(res => {
        this.groupList = res.data.data
      })
    },
    handleEdit(index, scope) {
      this.$store.commit('SHOW_LOADING')
      this.getGroupList()
      edit(scope.id).then(res => {
        this.$store.commit('HIDE_LOADING')
        if (!res.status) {
          this.$message.error(res.msg)
          return
        }
        const data = res.data
        this.form = {
          id: data.id,
          password: '',
          username: data.username,
          status: data.status === 1 ? '正常' : '禁用',
          gid: data.gid,
          nickname: data.nickname
        }
        this.selectUser = data.mid
        this.editVisible = true
      })
    },
    handleDelete(index, scope) {
      this.row = scope
      this.idx = index
      this.delVisible = true
    },
    deleteRow() {
      this.$store.commit('SHOW_LOADING')
      if (!this.isDelAll) {
        del(this.row.id).then(res => {
          this.$store.commit('HIDE_LOADING')
          if (!res.status) {
            this.$message.error(res.msg)
            return
          }
          this.tableData.splice(this.idx, 1)
          this.$message.success(res.msg)
        })
      } else {
        const id = this.delList.join('_')
        del(id).then(res => {
          this.$store.commit('HIDE_LOADING')
          if (!res.status) {
            this.$message.error(res.msg)
            return
          }
          this.delList = []
          this.isDelAll = false
          this.getUsers()
          this.$message.success(res.msg)
        })
      }
      this.delVisible = false
    },
    search() {
      this.getUsers()
    },
    currentChange(value) {
      this.current_page = value
      this.getUsers()
    },
    handleSelectionChange(values) {
      this.delList = []
      values.forEach(item => {
        this.delList.push(item.id)
      })
    },
    saveEdit(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          return false
        }
        if (this.form.status === '未审核') {
          this.form.status = 0
        }
        if (this.form.status === '正常') {
          this.form.status = 1
        }
        if (this.form.status === '被封') {
          this.form.status = 2
        }
        this.editVisible = false
        this.$store.commit('SHOW_LOADING')
        if (this.form.password === '') {
          delete this.form.password
        }
        save(this.form).then(res => {
          this.$store.commit('HIDE_LOADING')
          if (!res.status) {
            this.$message.error(res.msg)
            return
          }
          this.$refs[formName].resetFields()
          this.$message.success(res.msg)
          this.getUsers()
        })
      })
    },
    add() {
      this.getGroupList()
      this.editVisible = true
      this.form.id = 0
      this.form.password = ''
      this.form.username = ''
      this.form.status = '正常'
      this.form.gid = 1
      this.form.nickname = ''
    },
    cancel(formName) {
      this.$refs[formName].resetFields()
      this.form.status = '正常'
      this.editVisible = false
      this.form.id = 0
    },
    getUsers() {
      this.listLoading = true
      const where = []
      if (this.select_word) {
        where.push({ field: 'admin.username', op: 'like', value: this.select_word })
      }
      if (this.select_type !== '') {
        where.push({ field: 'admin.status', op: 'aeq', value: this.select_type })
      }
      if (this.select_date) {
        where.push({ field: 'admin.last_date', op: 'between', value: this.select_date })
      }
      getUsers({
        page: this.current_page,
        where: where
      }).then(res => {
        this.listLoading = false
        if (!res.status) return
        res = res.data
        this.tableData = res.data
        this.current_page = res.current_page
        this.totals = res.total
        this.per_page = res.per_page
        this.last_page = res.last_page
      })
    },
    handleAuth(index, scope) {
      console.log(index, scope)
    },
    resetPassword(index, scope) {},
    checkGroup(scope) {
      console.log(scope)
    }
  }
}
</script>
<style lang="scss" scoped>
.form {
  width: 90%;
  margin: 0 auto;
}
.handle-box {
  height: auto;
  overflow: hidden;
  padding-bottom: 10px;
  .handle-input {
    width: 150px;
    display: inline-block;
  }
  .handle-select {
    width: 80px;
    .del-dialog-cnt {
      font-size: 16px;
      text-align: center;
    }
  }
}
</style>
<style>
textarea.el-textarea__inner {
  height: 88px;
  resize: none;
}
.el-input--small .el-input__inner {
  width: 90%;
}
.el-cascader--small .el-input__suffix {
  right: 20px;
}
</style>
